﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using Thor.Common;

namespace Thor.Repository.Azure.Blob
{
    public abstract class BlobRepositoryBase : IRepository
    {
        #region Constants

        private const string CONTAINERADDRESS = "ContainerAddress";
        private const string CONNECTIONSTRING = "ConnectionString";

        #endregion

        #region Fields

        protected static CloudBlobClient _blobStorage;
        protected static bool _createdContainer = false;
        protected static object _lock = new Object();

        #endregion

        #region Constructors

        public BlobRepositoryBase(Dictionary<string, object> repositoryParameters)
        {
            RepositoryParameters = repositoryParameters;
        }

        #endregion

        #region Properties

        public CloudStorageAccount StorageAccount
        {
            get
            {
                if (RepositoryParameters[CONNECTIONSTRING] != null)
                    return CloudStorageAccount.FromConfigurationSetting(Convert.ToString(RepositoryParameters[CONNECTIONSTRING]));
                else
                    return null;
            }
        }

        public string ContainerAddress
        {
            get
            {
                if (RepositoryParameters[CONTAINERADDRESS] != null)
                    return Convert.ToString(RepositoryParameters[CONTAINERADDRESS]);
                else
                    return string.Empty;
            }
            set
            {
                if (RepositoryParameters[CONTAINERADDRESS] != null)
                    RepositoryParameters[CONTAINERADDRESS] = value;
            }
        }

        #endregion

        #region Methods

        private void CreateContainer()
        {
            if (_createdContainer)
                return;

            lock (_lock)
            {
                if (_createdContainer)
                    return;

                _blobStorage = this.StorageAccount.CreateCloudBlobClient();
                CloudBlobContainer container = _blobStorage.GetContainerReference(this.ContainerAddress);
                container.CreateIfNotExist();

                var permissions = container.GetPermissions();
                permissions.PublicAccess = BlobContainerPublicAccessType.Container;

                container.SetPermissions(permissions);

                _createdContainer = true;
            }
        }

        protected CloudBlobContainer GetContainer()
        {
            CreateContainer();
            return _blobStorage.GetContainerReference(this.ContainerAddress);
        }

        #endregion

        #region IRepository Members

        public Dictionary<string, object> RepositoryParameters { get; set; }

        #endregion
    }
}
